<template>
  <el-dialog :model-value="specialOpen" :title="specialTitle" :before-close="handleClose">
    <!-- 特殊产品管理 点击按钮栏的特殊产品展现的 -->
    <custom-container ref="customContainerRef" :config="mainConfig" />
    <!-- 新增修改特殊产品 -->
    <el-dialog
      v-model="open"
      :title="title"
      append-to-body
      :close-on-click-modal="false"
      width="600px"
    >
      <el-form
        ref="editForm"
        :rules="rules"
        :model="form"
      >
        <el-form-item label="销售产品" prop="salesProductsCode">
          <select v-model="form.salesProductsCode">
            <option
              v-for="item in productOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </option>
          </select>
        </el-form-item>
        <el-form-item label="起收重量" prop="liftingWeight">
          <el-input v-model="form.liftingWeight"></el-input>
        </el-form-item>
        <el-form-item label="单件补足重量" prop="underWeight">
          <el-input v-model="form.underWeight"></el-input>
        </el-form-item>
        <el-form-item label="单件材积补足重量" prop="woodWeight">
          <el-input v-model="form.woodWeight"></el-input>
        </el-form-item>
        <el-form-item label="大货价格调整" prop="bigPriceAdjustment">
          <el-input v-model="form.bigPriceAdjustment"></el-input>
        </el-form-item>
        <el-form-item label="小货价格调整" prop="smallPriceAdjustment">
          <el-input v-model="form.smallPriceAdjustment"></el-input>
        </el-form-item>
        <el-form-item label="最低单价" prop="pricesForSpecialProducts ">
          <el-input v-model="form.pricesForSpecialProducts"></el-input>
        </el-form-item>
        <el-form-item label="大货分泡材积系数" prop="specialVolumeCoefficient">
          <el-input v-model="form.specialVolumeCoefficient"></el-input>
        </el-form-item>
        <el-form-item label="小货分泡材积系数" prop="specialVolumeCoefficientSmall">
          <el-input v-model="form.specialVolumeCoefficientSmall"></el-input>
        </el-form-item>
        <el-form-item label="体积系数" prop="volunmFactor">
          <el-input v-model="form.volunmFactor" type="number"></el-input>
        </el-form-item>
        <el-form-item label="是否补足单件" prop="isSingle">
          <el-radio-group v-model="form.isSingle">
            <el-radio :label="'1'">是</el-radio>
            <el-radio :label="'0'">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否补足101" prop="isMakeUp">
          <el-radio-group v-model="form.isMakeUp">
            <el-radio :label="'1'">是</el-radio>
            <el-radio :label="'0'">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否生效" prop="smallGoodsSeparated">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dicts[DictDirection.通用状态]" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生效时间" prop="time">
          <el-date-picker
            v-model="form.time"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>
<script lang="ts" setup>
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
import { ref, getCurrentInstance, computed } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { getCus, addCus, updCus, delCus, getCusById, getProductList } from '@/api/clientManger'

const props = defineProps<{
productId
specialOpen
specialTitle
}>()
console.log(props.productId, 'code的编码')
const customContainerRef = ref(null)
const dicts = useDicts()
dicts.setDicts(DictDirection.通用状态)
// 新增-修改特殊产品状态
let  
  open = ref(false),
  // 新增-修改特殊产品名称
  title = ref(''),
  // 查询参数
  queryParams = {
    pageSize: 10,
    pageNum: 1,
    customerId: props.productId,
  },
  productOptions = ref([]),
  
  single = ref(true),
  rules = {
    time: [{ required: true, message: '请选择时间', trigger: 'change' }],
    salesProductsCode: [{ required: true, message: '必填', trigger: 'blur' }],
    liftingWeight: [{ required: true, message: '必填', trigger: 'blur' }],
    underWeight: [{ required: true, message: '必填', trigger: 'blur' }],
    specialVolumeCoefficient: [{ required: true, message: '必填', trigger: 'blur' }],
    specialVolumeCoefficientSmall: [{ required: true, message: '必填', trigger: 'blur' }],
    volunmFactor: [{ required: true, message: '必填', trigger: 'blur' }],
    woodWeight: [{ required: true, message: '必填', trigger: 'blur' }],
  },
  form = {
    status: '1',
    salesProductsCode: '',
    liftingWeight: undefined,
    specialVolumeCoefficient: undefined,
    bigPriceAdjustment: undefined,
    smallPriceAdjustment: undefined,
    pricesForSpecialProducts: undefined,
    solidWeightSeparated: undefined,
    smallGoodsSeparated: undefined,
    specialVolumeCoefficientSmall: undefined,
    underWeight: undefined,
    volunmFactor: undefined,
    isSingle: undefined,
    isMakeUp: undefined,
    woodWeight: 0,
    time: undefined,
    custCode: undefined,
    id: undefined,
  },
  {
    proxy,

  }:{
    proxy:any
 
  } = getCurrentInstance()
let ids = [],
  editForm = ref(undefined)
// 重置新增修改表单
const reast = () => {
  form = {
    status: '1',
    salesProductsCode: '',
    liftingWeight: undefined,
    specialVolumeCoefficient: undefined,
    bigPriceAdjustment: undefined,
    smallPriceAdjustment: undefined,
    pricesForSpecialProducts: undefined,
    solidWeightSeparated: undefined,
    smallGoodsSeparated: undefined,
    specialVolumeCoefficientSmall: undefined,
    underWeight: undefined,
    volunmFactor: undefined,
    isSingle: undefined,
    isMakeUp: undefined,
    woodWeight: 0,
    time: undefined,
    custCode: undefined,
    id: undefined,
  }
  proxy.$resetForm(editForm.value)
}
function handleClose(done) {
  emit('update:code', '')
  emit('update:specialOpen', false)
  done()
}
// 搜索
const handleQuery = () => {
  customContainerRef.value.getList()
}
// 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  ids = rows.map((item) => item.id)
  single.value = !rows.length
}
// 新增特殊产品
const handleAdd = () => {
  open.value = true
  title.value = '新增特殊产品'
}
// 修改特殊产品
const handleUpdate = (row: { [key: string]: any }) => {
  getCusById(row.id).then(res => {
    if (res.code == '200') {
      const { effectOfTime, theFailureTime } = res.data
      form.value = res.data
      proxy.$set(form.value, 'time', [])
      proxy.$set(form.value.time, 0, effectOfTime)
      proxy.$set(form.value.time, 1, theFailureTime)
      open.value = true
    }
  })
}
// 删除特殊产品
function handleDel(row:{[key:string]:any}) {
  const id = row.id || ids
  ElMessageBox.confirm(`是否确认删除特殊产品编号为"${ id }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => delCus(id))
  .then((res) => {
    if (res.code === 200) {
      console.log('ss')
      handleQuery()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.info(error)
    }
  })
}
// 确定-新增修改表单
const submit = () => {
  proxy.$refs.form.validate(valid => {
    if (valid) {
      form.custCode = props.productId
      if (form.id != undefined) {
        // 修改
        updCus(proxy.$addDateRange(form, form.time)).then(res => {
          if (res.code == '200') {
            ElMessage.success('修改成功')
            open.value = false
            reast()
            handleQuery()
          }
        })
      } else {
        // 新增
        addCus(proxy.$addDateRange(form, form.time)).then(res => {
          if (res.code == '200') {
            ElMessage.success('修改成功')
            open.value = false
            reast()
            handleQuery()
          }
        })
      }
    }
  })
}
const emit = defineEmits(['update:code', 'update:specialOpen'])
// 取消新增-修改表单
function cancel() {
  reast()
  open.value = false
  emit('update:code', [])
  emit('update:specialOpen', false)
}
// 查询所有销售产品
function getAllProductList() {
  const data = { pageNum: 1,
    pageSize: 10 }
  return getProductList(data).then(res => {
    productOptions.value = res.data
  })
}
getAllProductList()

// 主体配置
const mainConfig = computed(() => ({
  query: {
    fields: [
    ],
    queryParams,
  },
  btns: [
    {
      title: '新增',
      icon: Plus,
      type: 'success',
      directive: [['hasPermi', ['system:custWeighing:add']]],
      onClick: handleAdd,
    },
    {
      title: '修改',
      icon: Edit,
      type: 'primary',
      disabled: single.value,
      directive: [['hasPermi', ['system:custWeighing:edit']]],
      onClick: handleUpdate,
    },
     
  ],
  table: {
    columns: [
      { type: 'selection', width: '55', align: 'center' },
      {
        label: '销售产品',
        prop: 'salesProductsCode',
        align: 'center',
        width: '90',
      },
      {
        label: '起收重量',
        prop: 'liftingWeight',
        align: 'center',
      },
      {
        label: '单件补足重量',
        prop: 'underWeight',
        align: 'center',
      },
      {
        label: '单件材积补足重量',
        prop: 'woodWeight',
        align: 'center',
      },
      {
        label: '大货价格调整',
        prop: 'bigPriceAdjustment',
        align: 'center',
         
      },
      {
        label: '小货价格调整',
        prop: 'smallPriceAdjustment',
        align: 'center',
      },
      {
        label: '最低单价',
        prop: 'pricesForSpecialProducts',
        align: 'center',
      },
      {
        label: '大货分泡材积系数',
        prop: 'specialVolumeCoefficient',
        align: 'center',
      },
      {
        label: '小货分泡材积系数',
        prop: 'specialVolumeCoefficientSmall',
        align: 'center',
      },
      {
        label: '是否补足单件',
        prop: 'isSingle',
        align: 'center',
        formatter(row:{[key:string]:any}) {
          row.isSingle ? '是' : '否'
        },
      },
      {
        label: '是否补足101',
        prop: 'isMakeUp',
        align: 'center',
        formatter(row:{[key:string]:any}) {
          row.isMakeUp ? '是' : '否'
        },
      },
      {
        label: '状态',
        prop: 'status',
        align: 'center',
      },
      {
        label: '开始日期',
        prop: 'effectOfTime',
        align: 'center',
      },
      {
        label: '结束日期',
        prop: 'theFailureTime',
        align: 'center',
      },
      {
        label: '操作',
        align: 'center',
        showOverflowTooltip: false,
        render: (h, params) => {
          const buttons = [
            {
              title: '修改',
              icon: Edit,
              clickFun: handleUpdate,
              directive: [['hasPermi', ['system:custWeighing:edit']]],
            },
            {
              title: '删除',
              icon: Delete,
              clickFun: handleDel,
              directive: [['hasPermi', ['system:custWeighing:remove']]],
            },
          ]
          return buttons.map((el) => h(
            ElButton,
            {
              text: true,
              type: 'primary',
              icon: el.icon,
              onClick: () => {
                el.clickFun(params.row)
              },
            },
            {
              default: () => el.title,
            },
          ))
        },
      },
    ],
    event: {
      onSelectionChange: (rows) => {
        handleSelectionChange(rows)
      },
    },
  },
  api: getCus,

}))

</script>
